<?php
/**
 * Created by IntelliJ IDEA.
 * User: admin
 * Date: 5/31 0031
 * Time: 14:38
 */

namespace app\index\model;

use think\DB;
use think\Cache;

class Wx
{

    /**
     * 增加一个微信门店
     */
    public function addpoi($token)
    {
        $url = "http://api.weixin.qq.com/cgi-bin/poi/addpoi?access_token=$token";
        $post_str = json_encode([
            "buffer" => [
                "business" => [
                    "base_info" => [
                        "sid" => "33788392",
                        "business_name" => "15个汉字或30个英文字符内",
                        "branch_name" => "不超过10个字，不能含有括号和特殊字符",
                        "province" => "不超过10个字",
                        "city" => "不超过30个字",
                        "district" => "不超过10个字",
                        "address" => "门店所在的详细街道地址（不要填写省市信息）：不超过80个字",
                        "telephone" => "不超53个字符（不可以出现文字）",
                        "categories" => ["美食,小吃快餐"],
                        "offset_type" => 1,
                        "longitude" => 115.32375,
                        "latitude" => 25.097486,
                        "photo_list" => [
                            [
                                "photo_url" => "https://m.baidu.com"
                            ],
                            [
                                "photo_url" => "https://XXX.com"
                            ]
                        ],
                        "recommend" => "不超过200字。麦辣鸡腿堡套餐，麦乐鸡，全家桶",
                        "special" => "不超过200字。免费wifi，外卖服务",
                        "introduction" => "不超过300字。麦当劳是全球大型跨国连锁餐厅，1940 年创立于美国，在世界上大约拥有3万间分店。主要售卖汉堡包，以及薯条、炸鸡、汽水、冰品、沙拉、水果等快餐食品",
                        "open_time" => "8:00-20:00",
                        "avg_price" => 35
                    ]
                ]
            ]
        ]);
        return curl_post_json($url, $post_str);
    }

    /**
     * 设置白名单
     */
    public function testwhitelist($token, $username)
    {
        $url = "https://api.weixin.qq.com/card/testwhitelist/set?access_token=$token";
        $poststr = json_encode([
            "username" => [$username]
        ]);
        return curl_post($url, $poststr);
    }

    /**
     * 测试卡包创建SDK
     */
    public function testcard()
    {
        include_once EXTEND_PATH . "cardSDK.php";
        $base_info = new \BaseInfo("http://www.supadmin.cn/uploads/allimg/120216/1_120216214725_1.jpg", "海底捞",
            0, "132元双人火锅套餐", "Color010", "使用时向服务员出示此券", "020-88888888",
            "不可与其他优惠同享\n 如需团购券发票，请在消费时向商户提出\n 店内均可使用，仅限堂食\n 餐前不可打包，餐后未吃完，可打包\n 本团购券不限人数，建议2人使用，超过建议人数须另收酱料费5元/位\n 本单谢绝自带酒水饮料", new \DateInfo(1, 1397577600, 1399910400), new \Sku(50000000));
        $base_info->set_sub_title("");
        $base_info->set_use_limit(1);
        $base_info->set_get_limit(3);
        $base_info->set_use_custom_code(false);
        $base_info->set_bind_openid(false);
        $base_info->set_can_share(true);
        $base_info->set_url_name_type(1);
        $base_info->set_custom_url("http://www.qq.com");
//        dump($base_info);

        //---------------------------set_card--------------------------------

        $card = new \Card("GROUPON", $base_info);
        $card->get_card()->set_deal_detail("以下锅底2 选1（有菌王锅、麻辣锅、大骨锅、番茄锅、清补凉锅、酸菜鱼锅可选）：\n 大锅1 份12 元\n 小锅2 份16 元\n 以下菜品2 选1\n 特级肥牛1 份30 元\n 洞庭鮰鱼卷1 份20元\n 其他\n鲜菇猪肉滑1 份18 元\n 金针菇1 份16 元\n 黑木耳1 份9 元\n 娃娃菜1 份8 元\n 冬瓜1份6 元\n 火锅面2 个6 元\n 欢乐畅饮2 位12 元\n 自助酱料2 位10 元");

//--------------------------to json--------------------------------
        echo $card->toJson();
//
////----------------------check signature------------------------
//
//        $signature = new \Signature();
//        $signature->add_data( "875e5cc094b78f230b0588c2a5f3c49f" );
//        $signature->add_data( "wx57bf46878716c27e" );
//        $signature->add_data( "213168808" );
//        $signature->add_data( "12345" );
//        $signature->add_data( "55555" );
//        echo $signature->get_signature();
    }

    public function createQrcode($token)
    {
        $url = "https://api.weixin.qq.com/card/qrcode/create?access_token=$token";


        $code="66668888";
        $key=md5("uu"+time());
        $code=$code+$key;
     $t1=  DB::table('j_vipcode')->insert(array('code'=>$code,'num'=>0));
if(!$t1){

    return false;

}


        $poststr = json_encode([
            "action_name" => "QR_CARD",
            "expire_seconds" => 1800,
            "action_info" => [
                "card" => [
                    "code"=>$code,
                    "card_id" => "pTEJew86si3rOMvnIapBqOTWOVHE",
                    "openid" => "wxb629e35f0b63fef2",
                    "is_unique_code" => true,
                ]
            ]
        ]);
        return curl_post($url, $poststr);
    }

    /**
     * 增加一个会员卡
     * @param $post
     */
    public function addcard($merchantid, $post)
    {
        $token = $this->gettokenbyid($merchantid);
        $res = $this->cardtodatabase($post, $merchantid);//增加到数据库中
        if (empty($res)) {
            return ["status" => 0, "msg" => '录入失败'];
        }
        $res2 = $this->CardCreate($token, $post);//发送至接口
        $wxres=json_decode($res2);
        if($wxres->errcode!=0){
            return ["status"=>0,"msg"=>$wxres->errmsg];
        }
        model("Card")->isUpdate(true,["id"=>$res])->save([
            "card_id"=>$wxres->card_id
        ]);//更新到表中
        if (empty($res2)) {
            return ["status" => 0, 'msg' => "接口异常"];
        } else {
            return ["status" => 1, "msg" => "成功创建"];
        }
    }

    /**
     * @param $merchantid
     * @return mixed|string
     */
    public function gettokenbyid($merchantid)
    {
        $wxconfig = model("Wxconfig")->where("merchantid", $merchantid)->find();
        if (!empty($wxconfig)) {
            return $this->getAccessToken($wxconfig["appid"], $wxconfig["secret"]);
        } else {
            return "";
        }
    }

    /**
     * 获得ACCESSTOKIEN的值
     * @param $appid
     * @param $secret
     * @return mixed
     */
    public function getAccessToken($appid, $secret)
    {
        if (Cache::get("access_token_$appid")) {
            $access_token = Cache::get("access_token_$appid");
        } else {
            $tokenrequest = curl_get("https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret");
            $getdata = json_decode($tokenrequest, true);
            if (isset($getdata["access_token"])) {
                $access_token = $getdata["access_token"];
                Cache::set("access_token_$appid", $access_token, $getdata["expires_in"] - 200);
            } else {
                die($getdata["errmsg"]);
            }
        }
        return $access_token;
    }

    /**
     * 卡信息记录到数据库
     */
    public function cardtodatabase($data, $merchantid)
    {
        $dev = [];
        //先保存到数据库中
        $dev["logourl"] = $data["logo_url"];
        $dev['cardname'] = $data["cardname"];
        $dev['subname'] = $data["subname"];
        if (isset($data["bgstyle"]) and $data["bgstyle"] == "1") {
            $dev['bgimg'] = $data["background_pic_url"];
        }
        $dev['bgcolor'] = $data["color"];//必填项
        $dev['isforver'] = $data["isforver"];
        if ($data["isforver"] == "0") {
            $dev['starttime'] = strtotime($data["starttime"]);
            $dev['endtime'] = strtotime($data["endtime"]) + 3600 * 24-1;//剪掉一秒
        }
        $dev['grantnum'] = $data["grantnum"];
        $dev['isdiscount'] = isset($data["isdiscount"]) ? $data["isdiscount"] : 0;
        $dev['isintegral'] = isset($data["isintegral"]) ? $data["isintegral"] : 0;
        $dev['ischarge'] = isset($data["ischarge"]) ? $data["ischarge"] : 0;
        $dev['isallshop'] = isset($data["isallshop"]) ? $data["isallshop"] : 0;
        $dev['privilege'] = $data["privilege"];
        $dev['instructions'] = $data["instructions"];
        $dev["notice"] = $data["notice"];
        $dev['servicetel'] = $data["servicetel"];
        $dev['desimg'] = isset($data["desimg"]) ? $data['desimg'] : "";
        $dev['destext'] = isset($data["destext"]) ? $data['destext'] : "";
        $dev['merchantid'] = $merchantid;
        model("Card")->save($dev);
        $cardid = model("Card")->getLastInsID();
        if (!!$dev['isdiscount']) {
            model("Carddiscount")->save(["cardid" => $cardid, "value" => $data["discountvalue"]]);
        }
        if (!!$dev['isintegral']) {
            model("Cardintegral")->save([
                "cardid" => $cardid,
                "activation" => $data["activation"],
                "pernum" => $data["pernum"],
                "giveintegral" => $data["giveintegral"]
            ]);
        }
        if (!!$dev['ischarge']) {
            $chargearr = [];
            foreach ($data["gradient"] as $k => $v) {
                $chargearr[] = [
                    "cardid" => $cardid,
                    "gradient" => $v,
                    "backmoney" => $data["backmoney"][$k]
                ];
            }
            model("Cardcharge")->saveAll($chargearr);
        }
        if (!!$dev['isallshop']) {
            $shopid = [];
            foreach ($data['shopid'] as $v) {
                $shopid[] = ["cardid" => $cardid, "shopid" => $v];
            }
            model("Cardshop")->saveAll($shopid);
        }
        return $cardid;
    }

    /**
     * 创建会员卡
     */
    public function CardCreate($token, $data)
    {
        include_once EXTEND_PATH . "cardSDK.php";
        if ($data["isforver"] == "1") {
            $data_info = new \DateInfo(2, time());
        } else {
            $data_info = new \DateInfo(1, strtotime($data["starttime"]), strtotime($data["endtime"]) + 3600 * 24);
        }
        //然后发送到微信接口
        $url = "https://api.weixin.qq.com/card/create?access_token=$token";
        $base_info = new \BaseInfo($data["logo_url"], $data["subname"], "CODE_TYPE_QRCODE", $data["cardname"], $data["color"], $data["notice"], $data["servicetel"], $data["instructions"], $data_info, new \Sku($data["grantnum"]));
        $base_info->set_sub_title("");
        $base_info->set_use_limit(1);//每人先用一张
        $base_info->set_get_limit(1);//每人限领3张
        $base_info->set_use_custom_code(true);//使用自定义CODE
        $base_info->set_bind_openid(false);
        $base_info->set_can_share(false);//不可分享
        $base_info->set_can_give_friend(false);//不可转赠
        $base_info->set_url_name_type(1);
        $base_info->set_custom_url_name("会员主页");
        $base_info->set_custom_url("http://xtshop.xwdcook.com");
        $base_info->set_custom_url_sub_title("立即进入");
        //---------------------------set_card--------------------------------
        $card = new \Card("MEMBER_CARD", $base_info);
//        $card->get_card()->set_deal_detail("以下锅底2 选1（有菌王锅、麻辣锅、大骨锅、番茄锅、清补凉锅、酸菜鱼锅可选）：\n 大锅1 份12 元\n 小锅2 份16 元\n 以下菜品2 选1\n 特级肥牛1 份30 元\n 洞庭鮰鱼卷1 份20元\n 其他\n鲜菇猪肉滑1 份18 元\n 金针菇1 份16 元\n 黑木耳1 份9 元\n 娃娃菜1 份8 元\n 冬瓜1份6 元\n 火锅面2 个6 元\n 欢乐畅饮2 位12 元\n 自助酱料2 位10 元");
        $card->get_card()->set_prerogative($data["privilege"]);//会员卡特权说明
        $card->get_card()->set_supply_bonus(true);//显示积分
//        $card->get_card()->set_bonus_url("http://mail.qq.com");//积分自定义网址,会不显示
        $card->get_card()->set_supply_balance(true);//是否支持储值
//        $card->get_card()->set_balance_url("http://qzone.qq.com");//余额自定义网址,会不显示
        $card->get_card()->set_custom_field1([
            'name_type' => "FIELD_NAME_TYPE_DISCOUNT",
            'url' => "http://www.xcsbuy.cn"
        ]);
//        $card->get_card()->set_wx_activate(true);//普通一键激活
//        $card->get_card()->set_auto_activate(true);//自动激活
        $card->get_card()->set_activate_url("http://www.baidu.com");//激活会员卡的URL 不能为空
        if (isset($data["bgstyle"]) and $data["bgstyle"] == "1") {
            $card->get_card()->set_background_pic_url($data["background_pic_url"]);
        }
        //折扣优惠
        if (isset($data["isdiscount"]) ? $data["isdiscount"] : 0) {
            $card->get_card()->set_discount(100 - $data["discountvalue"] * 10);
        }
        //积分优惠,注意复数
        if (isset($data["isintegral"]) ? $data["isintegral"] : 0) {
            $card->get_card()->set_bonus_rule([
                'cost_money_unit' => $data["pernum"] * 100,
                'increase_bonus' => $data["giveintegral"],
                'init_increase_bonus' => $data["activation"]
            ]);
        }
        $desimg = isset($data["desimg"]) ? $data['desimg'] : "";
        $destext = isset($data["destext"]) ? $data['destext'] : "";
        if ($destext || $desimg) {
            $card->get_card()->set_advanced_info(
                ['text_image_list' => [
                    [
                        'image_url' => $desimg,
                        'text' => $destext
                    ]
                ]
                ]);//设置高级信息
        }

        echo $card->toJson();
        echo PHP_EOL;
//--------------------------to json--------------------------------
        return curl_post($url, $card->toJson());
//        $post_str = json_encode(
//            [
//                'card' => [
//                    'card_type' => "MEMBER_CARD",//
//                    'member_card' => [
//                        'background_pic_url' => "https://mmbiz.qlogo.cn/mmbiz/",
//                        'base_info' => [
//                            'logo_url' => "http://mmbiz.qpic.cn/mmbiz/iaL1LJM1mF9aRKPZ/0",
//                            'brand_name' => "海底捞",
//                            'code_type' => "CODE_TYPE_TEXT",
//                            'title' => "海底捞会员卡",
//                            'color' => "Color010",
//                            'notice' => "使用时向服务员出示此券",
//                            'service_phone' => "020-88888888",
//                            'description' => "不可与其他优惠同享",
//                            'date_info' => [
//                                'type' => "DATE_TYPE_PERMANENT"
//                            ],
//                            'sku' => [
//                                'quantity' => 50000000
//                            ],
//                            'get_limit' => 3,
//                            'use_custom_code' => 0,
//                            'can_give_friend' => 1,
//                            'location_id_list' => [123, 12321],
//                            'custom_url_name' => "立即使用",
//                            'custom_url' => "http://weixin.qq.com",
//                            'custom_url_sub_title' => "6个汉字tips",
//                            'promotion_url_name' => "营销入口1",
//                            'promotion_url' => "http://www.qq.com",
//                            'need_push_on_view' => 1
//                        ],
//                        'advanced_info' => [
//                            'use_condition' => [
//                                'accept_category' => "鞋类",
//                                'reject_category' => "阿迪达斯",
//                                'can_use_with_other_discount' => 1
//                            ],
//                            'abstract' => [
//                                'abstract' => "微信餐厅推出多种新季菜品，期待您的光临",
//                                'icon_url_list' => [
//                                    "http://mmbiz.qpic.cn/mmbiz/p98FjXy8LacgHxp3sJ3vn97bGLz0ib0Sfz1bjiaoOYA027iasqSG0sj  piby4vce3AtaPu6cIhBHkt6IjlkY9YnDsfw/0"
//                                ]
//                            ],
//                            'text_image_list' => [
//                                [
//                                    'image_url' => "http://mmbiz.qpic.cn/mmbiz/p98FjXy8LacgHxp3sJ3vn97bGLz0ib0Sfz1bjiaoOYA027iasqSG0sjpiby4vce3AtaPu6cIhBHkt6IjlkY9YnDsfw/0",
//                                    'text' => "此菜品精选食材，以独特的烹饪方法，最大程度地刺激食 客的味蕾"
//                                ],
//                                [
//                                    'image_url' => "http://mmbiz.qpic.cn/mmbiz/p98FjXy8LacgHxp3sJ3vn97bGLz0ib0Sfz1bjiaoOYA027iasqSG0sj piby4vce3AtaPu6cIhBHkt6IjlkY9YnDsfw/0",
//                                    'text' => "此菜品迎合大众口味，老少皆宜，营养均衡"
//                                ]
//                            ],
//                            'time_limit' => [
//                                [
//                                    'type' => "MONDAY",
//                                    'begin_hour' => 0,
//                                    'end_hour' => 10,
//                                    'begin_minute' => 10,
//                                    'end_minute' => 59
//                                ],
//                                [
//                                    'type' => "HOLIDAY"
//                                ]
//                            ],
//                            'business_service' => [
//                                "BIZ_SERVICE_FREE_WIFI",
//                                "BIZ_SERVICE_WITH_PET",
//                                "BIZ_SERVICE_FREE_PARK",
//                                "BIZ_SERVICE_DELIVER"
//                            ]
//                        ],
//                        'supply_bonus' => 1,
//                        'supply_balance' => 2,
//                        'prerogative' => "test_prerogative",
//                        'auto_activate' => 1,
//                        'custom_field1' => [
//                            'name_type' => "FIELD_NAME_TYPE_LEVEL",
//                            'url' => "http://www.qq.com"
//                        ],
//                        'activate_url' => "http://www.qq.com",
//                        'custom_cell1' => [
//                            'name' => "使用入口2",
//                            'tips' => "激活后显示",
//                            'url' => "http://www.xxx.com"
//                        ],
//                        'bonus_rule' => [
//                            'cost_money_unit' => 100,
//                            'increase_bonus' => 1,
//                            'max_increase_bonus' => 200,
//                            'init_increase_bonus' => 10,
//                            'cost_bonus_unit' => 5,
//                            'reduce_money' => 100,
//                            'least_money_to_use_bonus' => 1000,
//                            'max_reduce_bonus' => 50
//                        ],
//                        'discount' => 10
//                    ]
//                ]
//            ]);

    }

    /**
     * 用来更新会员卡信息接口
     * @param $token
     * @return mixed
     */
    public function updateuser($token)
    {
        $url = "https://api.weixin.qq.com/card/membercard/updateuser?access_token=$token";
        $poststr = json_encode([
            "code" => "304541678463",
            "card_id" =>"pTEJew3RRHefsjuaycCKFo7CeyNI",
            "record_bonus" => "消费30元,获得36积分",
            "bonus" => 300,
            "add_bonus" => 40,
            "balance" => 1000,
            "add_balance" => 60,
            "record_balance" => "购买焦糖,扣除10元",
            "notify_optional" => [
                "is_notify_bonus" => true,
                "is_notify_balance" => true
            ]
        ], JSON_UNESCAPED_UNICODE);
        return curl_post($url, $poststr);
    }

    /**
     * 获得一个自定义CODE
     * @return string
     */
    public function getacode(){
        do{
            $code=generatecode();
            $res=model("Cardcode")->where("code",$code)->find();//查询是否存在这个code
        }while(!empty($res));
        return $code;
    }

}